package com.cino.demos.service;

import com.cino.demos.entity.shortlink.Link;
import com.cino.demos.mapper.shortlink.ShortLinkMapper;
import com.cino.demos.shortlink.utils.UrlShortener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


@Service
public class ShortLinkService {

    @Autowired
    ShortLinkMapper shortLinkMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void shortLinkJump(HttpServletRequest request, HttpServletResponse response, Integer id) throws IOException {
//        String url = "https://gitee.com/cino333";
//        String shortLink = createShortLink(url);
//        int id = 1;
        Link dbLink = shortLinkMapper.selectById(id);
        String domain = dbLink.getDomain();
        String shortUrl = dbLink.getShortUrl();
        String fullUrl = domain + "/" + shortUrl;
        String origin = shortLinkMapper.selectByFullUrl(fullUrl);
        System.out.println(origin);
        String dbOrigin = dbLink.getOriginUrl();
        System.out.println(dbOrigin);
        response.sendRedirect(origin);
    }

    public String createShortLink(String url) {
        String shortenUrl = UrlShortener.shortenUrl(url);
        return shortenUrl;
    }

    public void insert() {
//        String originalUrl = "https://www.bilibili.com/video/BV1vf421i7hV?spm_id_from=333.788.videopod.episodes&vd_source=5951f25d79b162d0d6918adcc1984db1&p=31";
//        String shortenUrl = UrlShortener.shortenUrl(originalUrl);
//        String domain = "https://gitee.com/cino333";
//        Link link = Link.builder()
//                .domain(domain)
//                .shortUrl(shortenUrl)
//                .fullShortUrl(domain + "/" + shortenUrl)
//                .originUrl(originalUrl)
//                .build();
//        //第一版本：只能拿到整个Link的to.String()信息
////        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
////        rabbitTemplate.convertAndSend("Queue",(Object) JSON.toJSONString(link),correlationData);
//
//        //第二版本
//        // 发送消息
//        CorrelationData correlationData = new CorrelationData(UUID.randomUUID().toString());
//        MessageProperties messageProperties = new MessageProperties();
//        messageProperties.setCorrelationId(correlationData.getId());
//        String jsonLink = JSON.toJSONString(link);
//        Message message = new Message(jsonLink.getBytes(), messageProperties);
//        rabbitTemplate.send("Queue", message);

//        shortLinkMapper.insert(link);
    }
}
